﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using Cloak.Reflection;
using Ruleweaver.Conditions;

namespace Ruleweaver.Annotation
{
	public class AnnotatedConditionSource : DeclaredConditionSource
	{
		private readonly Type _targetType;
		private readonly string _defaultConditionName;

		public AnnotatedConditionSource(Type targetType)
		{
			Contract.Requires(targetType != null);

			_targetType = targetType;

			var defaultConditionNameAttribute = targetType.GetAttribute<DefaultConditionNameAttribute>();

			_defaultConditionName = defaultConditionNameAttribute == null ? null : defaultConditionNameAttribute.Name;
		}

		public override Type TargetType
		{
			get { return _targetType; }
		}

		protected override IEnumerable<IConditionDeclaration> GetDeclarations(MemberInfo member)
		{
			var declarations = member.GetAttributes<CheckAttribute>().Cast<IConditionDeclaration>();

			if(_defaultConditionName != null)
			{
				declarations = declarations.WithDefaultName(_defaultConditionName);
			}

			return declarations;
		}
	}
}